package org.csu.webjpetstoreback.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.webjpetstoreback.config.CommonResponse;
import org.csu.webjpetstoreback.model.*;
import org.csu.webjpetstoreback.service.ItemService;
import org.csu.webjpetstoreback.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

@RestController
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private Account account;

    @Autowired
    private Cart cart;

    @Autowired
    private Orders orders;

    @GetMapping("/Orders")
    public CommonResponse<List<Orders>> GetOrders(){
        return ordersService.GetOrders();
    }

    @GetMapping("/Orders/{id}")
    public CommonResponse<Orders> GetOrdersById(@PathVariable("id") int orderId){
            return ordersService.GetOrdersByID(orderId);
    }
    //下面两个解决orders自增问题
    @PostMapping("/Orders")
    public CommonResponse<Orders> PostOrder(@RequestBody Orders orders){
        return ordersService.PostOrders(orders);
    }
    @PutMapping("/Orders")
    public CommonResponse<Orders> PutOrder(@RequestBody Orders orders){
        return ordersService.PutOrders(orders);
    }

    @DeleteMapping("/Orders/{id}")
    public CommonResponse<Orders> DeleteOrder(@PathVariable("id") int orderId){
        return ordersService.DeleteOrders(orderId);
    }

    @GetMapping("/orders/newOrderForm")
    public CommonResponse<List<Orders>> newOrderForm(
            HttpSession session
    ){
        List<Orders> orderList = new ArrayList<>();
        //如果用自动注入的方式返回，会有很多其他的键值对，还不知道怎么去掉这些数据。所以这边还是用新建订单对象的方式。
        account = (Account) session.getAttribute("account");
        cart = (Cart) session.getAttribute("cart");
        String message="";

        /**
         * 测试代码1，将account和cart自定义数据用来测试代码逻辑性
         * 结论：可以正常返回orderList的数据！
         */
        /*
        account = new Account("j2ee","abc@qq.com","chen","long","1000",
                              "china","hunan","changsha","csu","1101"
                             ,"china","120","dog");
        Item item = new Item("CSG-1","JL-01",new BigDecimal(18.5),new BigDecimal(12),1,
                             "p","雄性锦鲤","好","好","好","好");
        cart = new Cart();
        cart.addItem(item,true);
        session.setAttribute("account",account);
        session.setAttribute("cart",cart);
        //测试代码2
        //结论，可以正常返回message和对应的status
        //account=null;
        //cart=null;
         */
        /**
         * 测试代码结束
         */

        if (account == null){
            /**账户为空的情况**/
            System.out.println("test1: account is null");
            message="You must sign on before attempting to check out.  Please sign on and try checking out again.";
            session.setAttribute("message", message);
            return CommonResponse.BackForError(message);
        }else if (cart != null){
            /**账户和购物车都不为空的情况**/
            Orders order = new Orders();
            order.initOrder(account,cart);
            //这里其实订单还没有生成，订单号没有给的，订单号默认是0.
            session.setAttribute("order",order);
            System.out.println("第一次session值："+session.getId());
            orderList.add(order);
            /**日志相关信息(暂时空着)**/

            /**这里可以返回正确的信息了，也就是Order的信息。**/
            return CommonResponse.BackForSuccess(orderList);
        }else{
            /**账户不为空但购物车为空的情况**/
            message="An order could not be created because a cart could not be found.";
            session.setAttribute("message", message);
            return CommonResponse.BackForError(message);
        }
    }

    @GetMapping("orders/payForm")
    public CommonResponse<List<Orders>> payForm(
            HttpSession session
    ) {
        String InventoryNumberMsg = new String();
        List<Orders> orderList = new ArrayList<>();
        Orders orders1 = new Orders();
        System.out.println("enter to payForm from payFormServlet");
        //实现数据库中的库存减一
        System.out.println("第二次session值："+session.getId());
        orders1 = (Orders) session.getAttribute("order");
        System.out.println("this order line quantity in payForm is: " + orders1.getLineItems().get(0).getQuantity());
        //用foreach遍历lineItems
        boolean InventoryNumberFlag = true;
        for (LineItem lineItem : orders1.getLineItems()) {
            //获取到itemId
            String itemId = lineItem.getItemId();
            //接下来要查找库存表
            Integer increment = Integer.valueOf(lineItem.getQuantity());
            String increment1 = Integer.toString(increment);
            System.out.println("itemId in payForm: " + itemId);
            System.out.println("increment in payForm: " + increment1);
            //这里其实还应该有一个逻辑，如果我需要买的数量大于现有的库存，那么我不应该让他买
            //调用ItemService的方法
            int QuantityNow = itemService.getInventoryByItemId(itemId).getData().getQty();
            System.out.println("QuantityNow in payForm: " + QuantityNow);
            session.setAttribute("InventoryNumberMsg", null);
            if (increment > QuantityNow) {
                System.out.println(itemId + " 的库存数量小于需要购买的数量，请减少购买数量! 当前的库存数量是：" + QuantityNow);
                InventoryNumberMsg += itemId + " 的库存数量小于需要购买的数量，请减少购买数量! 当前的库存数量是：" + QuantityNow;
                InventoryNumberFlag = false;
            }
        }
        System.out.println("InventoryNumberFlag is: " + InventoryNumberFlag);
        if (!InventoryNumberFlag) {
            session.setAttribute("InventoryNumberMsg", InventoryNumberMsg);
            /**
             * 第一个返回
             */
            return CommonResponse.BackForError(InventoryNumberMsg);
        } else {
            //更新库存
            for (LineItem lineItem : orders1.getLineItems()) {
                //获取到itemId
                String itemId = lineItem.getItemId();
                //接下来要查找库存表
                Integer increment = Integer.valueOf(lineItem.getQuantity());
                String increment1 = Integer.toString(increment);
                Map<String, String> param = new HashMap<String, String>(2);
                param.put("itemId", itemId);
                param.put("increment", increment1);
                itemService.updateInventoryQuantity(param);
            }
            /**
             * 将新订单插入数据库中去
             */
            //这里插入订单时，订单号会递增生成
            //这里我要改一下逻辑了，没有办法，我得把这句话调到确认支付那里了。
            //这里是把order插入到数据库中去了,实际上逻辑不对，还是应该改到payFormServlet中去
            //这里还没写好，因为要把sequence写好才能写订单ID编号的自增，所以我这里就写个测试用个随机数吧。
            int randomNumber = ThreadLocalRandom.current().nextInt(2000, 30001);
            orders1.setOrderId(randomNumber);
            orders1.setState("已付款");
            orders1.setSendOut("未发货");
            ordersService.PostOrders(orders1);
            orderList.add(orders1);
            System.out.println("order has been inserted in DB from payFormServlet");
            return CommonResponse.BackForSuccess(orderList);
        }
    }

    /**
     * 通过session中的账户名来获取orderList，对应viewListOrderServlet。
     * @param session
     * @return
     */
    @GetMapping("orders/OrderList")
    public CommonResponse<List<Orders>> getOrderListByUserName(
            HttpSession session
    ){
        /**
         * 测试account的数据来自NewOrderForm的请求中
         */
        Account account1 = (Account)session.getAttribute("account");
        String name = account1.getUserid();
        System.out.println("account1 name is:"+name);
        CommonResponse<List<Orders>> commonResponse = ordersService.GetOrdersByUserName(name);
        System.out.println(commonResponse);
        return commonResponse;
    }

    /**
     * 处理发货的逻辑
     */
     @GetMapping("orders/sendOut")
     public CommonResponse<List<Orders>> sendOut(
             HttpSession session,
             @RequestParam("orderid") int orderID
     ){
         Orders order = ordersService.GetOrdersByOrderId(orderID);
         if (order.getSendOut().equals("未发货")){
             session.setAttribute("msgListOrder","商家还未发货，请等待发货");
             return CommonResponse.BackForError("商家还未发货，请等待发货");
         }else {
             /**
              * 商家发货了，也点击确认收货了，那么订单状态要变成已完成
              */
             order.setState("已完成");
             //修改了数据库信息
             ordersService.PutOrdersByOrderId(orderID);
             //重新获取所有值并返回到前端！
             Account account1 = (Account)session.getAttribute("account");
             String name = account1.getUserid();
             System.out.println("account1 name is:"+name);
             CommonResponse<List<Orders>> commonResponse = ordersService.GetOrdersByUserName(name);
             System.out.println(commonResponse);
             return commonResponse;
         }
     }
}
